package ch.fusun.baron.basic.initialization;

import java.util.HashMap;
import java.util.Map;

import ch.fusun.baron.basic.messages.Messages;
import ch.fusun.baron.coatofarms.ui.CoatOfArmsData;
import ch.fusun.baron.core.initialization.GameInitializer;
import ch.fusun.baron.core.injection.Configure;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.core.rmi.User;
import ch.fusun.baron.core.service.UserService;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.Gender;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.Country;
import ch.fusun.baron.player.api.CountryService;
import ch.fusun.baron.player.api.MarriageService;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.printing.MessagingService;
import ch.fusun.baron.property.api.PropertyService;

/**
 * Adds a player for each user
 */
public class PlayerInitializer implements GameInitializer {

	@Configure(value = "16")
	private int INITIAL_AGE_MAN;
	@Configure(value = "16")
	private int INITIAL_AGE_WOMAN;
	@Inject
	private transient UserService userService;
	@Inject
	private transient PlayerService playerService;
	@Inject
	private transient MessagingService messagingService;
	@Inject
	private transient MarriageService marriageService;
	@Inject
	private transient CountryService countryService;
	@Inject
	private transient PropertyService propertyService;

	private final Map<User, String> userDynastyMap = new HashMap<User, String>();
	private final Map<User, CoatOfArmsData> userCOADynastyMap = new HashMap<User, CoatOfArmsData>();

	/**
	 * Constructor
	 */
	public PlayerInitializer() {
		// Do nothing
	}

	@Override
	public void initialize() {
		for (User user : userService.getUsers()) {
			createDynastyForUser(user);
		}
		messagingService.addMessage(null,
				Messages.PlayerInitializer_PlayersInitialized);
	}

	private void createDynastyForUser(User user) {
		Dynasty dynasty = new Dynasty(
				userDynastyMap.get(user) == null ? user.getName()
						: userDynastyMap.get(user), userCOADynastyMap.get(user));
		Country country = countryService
				.createCountry(userDynastyMap.get(user));
		Player man = playerService.generateNewPlayer(Gender.MALE);
		man.setAge(INITIAL_AGE_MAN);
		Player woman = playerService.generateNewPlayer(Gender.FEMALE);
		woman.setAge(INITIAL_AGE_WOMAN);
		dynasty.addPlayer(man);
		dynasty.addPlayer(woman);
		marriageService.marry(man, woman);
		playerService.setDynastyForUser(dynasty, user);
		propertyService.setOwnership(man, country);
	}

	/**
	 * @param user
	 *            The user
	 * @param name
	 *            The name
	 */
	public void setDynastyName(User user, String name) {
		userDynastyMap.put(user, name);
	}

	/**
	 * @param user
	 *            The user
	 * @param data
	 *            The data
	 */
	public void setDynastyCoatOfArms(User user, CoatOfArmsData data) {
		userCOADynastyMap.put(user, data);
	}
}
